package com.cangsan.erhai.security;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cangsan.erhai.common.R;
import com.cangsan.erhai.entity.SysMenu;
import com.cangsan.erhai.entity.SysRole;
import com.cangsan.erhai.entity.SysUser;
import com.cangsan.erhai.util.JwtUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Component
public class WechatAuthSuccessHandler implements AuthenticationSuccessHandler {


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();
        WechatAuthenticationToken wechatAuthenticationToken =(WechatAuthenticationToken) authentication;
       SysUser user= (SysUser) wechatAuthenticationToken.getPrincipal();
        String token = JwtUtils.genJwtToken(user.getOpenId());
        user.setOpenId(null);
        R r = R.ok("登录成功");
        Map<String,Object> tokenMap = new HashMap<>();
        tokenMap.put("authorization",token);
        tokenMap.put("currnetUser",user);
        r.setData(tokenMap);
        String jsonToken = JSONUtil.toJsonStr(r);
        outputStream.write(jsonToken.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
